
class PaymentService

  class << self

    def do_pay payment
      Payment.transaction do
        payment.save! if payment.new_record?
        log_payment_history(payment)
      end
    end

    def normal_pay_callback order
      Payment.transaction do
        order.complete_pay!
        OrderService.log_order_history(order)

        payment = order.payment

        payment.complete_pay!
        log_payment_history(payment)
      end
    end

    def chuang_pay_callback order
      Payment.transaction do
        pay_for_chuang(order)
        # TODO 窗管家下单失败？
        send_to_chuang(order)
        OrderService.log_order_history(order)
        log_payment_history(order.payment)
      end
    end

    def log_payment_history payment
      history = payment.payment_histories.build(
        payment_type: payment.current_state.to_s,
        amount: payment.total_money
      )
      history.save!
    end

    private

    def send_to_chuang(order)
      order.to_survey! if order.down_payment?
      true
    end

    def pay_for_chuang order
      payment = order.payment
      if order.unpaid?
        order.down_pay!

        payment.down_pay!

        Role.get_admin_users.each do |user|
          SmsService.reserve_msg_to_admin(user.mobile, order.order_no, order.reserve.address.cellphone)
        end
      elsif order.survey_completed?
        order.tail_pay!

        payment.tail_pay!
      else
      end
    end

  end

end
